import type { ProFormInstance } from '@ant-design/pro-form';
import ProForm, { ProFormText } from '@ant-design/pro-form';
import { message, Modal } from 'antd';
import React, { useEffect, useRef } from 'react';
import { createUser, updateUser } from '../service';

export default function BasicModal(props: any) {
  const { visible, handleCancel, user } = props;
  console.log(user);

  const formRef = useRef<ProFormInstance>();
  useEffect(() => {
    formRef?.current?.setFieldsValue(user);
  }, [user]);

  const create = async (values: any) => {
    const res = await createUser(values);
    if (res.status_code !== undefined) {
      message.error('操作失败');
    }
    message.success('操作成功');
    handleCancel();
  };

  const edit = async (id: string, values: any) => {
    const res = await updateUser(id, values);
    if (res.status_code !== undefined) {
      message.error('操作失败');
    }
    message.success('操作成功');
    handleCancel();
  };

  const handleOk = (values: any) => {
    return user?.id ? edit(user.id, values) : create(values);
  };

  return (
    <>
      <Modal
        title={user?.id ? '编辑' : '新增'}
        visible={visible}
        onCancel={handleCancel}
        footer={null}
        destroyOnClose
      >
        <ProForm onFinish={handleOk} formRef={formRef}>
          <ProFormText
            width="md"
            name="name"
            label="昵称"
            placeholder="请输入昵称"
            rules={[{ required: true, message: '请输入昵称' }]}
          />
          <ProFormText
            width="md"
            name="email"
            label="邮箱"
            placeholder="请输入邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入合法的邮箱' },
            ]}
          />
          {!user ? (
            <ProFormText.Password
              width="md"
              name="password"
              label="密码"
              placeholder="请输入密码"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, message: '密码最小长度为6位' },
              ]}
            />
          ) : (
            ''
          )}
        </ProForm>
      </Modal>
    </>
  );
}
